package com.zhss.netty.discard;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @ClassName NettyDiscardServer
 * @Description TODO
 * @Author leejiliang
 * @DateTime 2021/9/7 16:11
 * @Version 1.0
 */
public class NettyDiscardServer {
	private final int serverPort;
	ServerBootstrap b = new ServerBootstrap();
	public NettyDiscardServer(int serverPort) {
		this.serverPort = serverPort;
	}

	public void runServer() {
		NioEventLoopGroup bossLoopGroup = new NioEventLoopGroup(1);
		NioEventLoopGroup workerLoopGroup = new NioEventLoopGroup();
		try {

			b.group(bossLoopGroup, workerLoopGroup);
			b.channel(NioServerSocketChannel.class);
			b.localAddress(serverPort);
			b.option(ChannelOption.SO_KEEPALIVE, true);
			b.childHandler(new ChannelInitializer<SocketChannel>() {
				protected void initChannel(SocketChannel socketChannel) throws Exception {
					socketChannel.pipeline().addLast(new NettyDiscardHandler());
				}
			});
			ChannelFuture channelFuture = b.bind().sync();
			System.out.println("服务器启动成功, 监听端口: " + channelFuture.channel().localAddress());
			ChannelFuture closeFuture = channelFuture.channel().closeFuture();
			closeFuture.sync();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			workerLoopGroup.shutdownGracefully();
			bossLoopGroup.shutdownGracefully();
		}
	}

	public static void main(String[] args) {
		new NettyDiscardServer(9000).runServer();
	}

}
